﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.SqlClient;

namespace TestSQLWithTLSPro
{
  public partial class Form1 : Form
  {
    private const string ConnProviderName = "System.Data.SqlClient";
    DbProviderFactory dbfactory = null;
    private DbConnection connection = null;
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      //richTextBox1.Text = "";
      //connection = CreateConnection(ConnProviderName, richTextBox1.Text);

      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = textBox1.Text;
      builder.Encrypt = checkBox1.Checked;
      builder.TrustServerCertificate = checkBox2.Checked;
      builder.InitialCatalog = textBox2.Text;
      builder.PersistSecurityInfo = checkBox3.Checked;
      builder.UserID = textBox3.Text;
      builder.Password = textBox4.Text;

      richTextBox1.Text = builder.ToString();
      

    }

    private void button2_Click(object sender, EventArgs e)
    {
      connection = new SqlConnection(richTextBox1.Text);
      
      dbfactory = DbProviderFactories.GetFactory(ConnProviderName);
      DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();

      dbDataAdapter.SelectCommand = GetDbSqlCommand(richTextBox2.Text);

      DataTable dataTable = new DataTable();

      //dbDataAdapter.FillSchema(dataTable, SchemaType.Mapped);
      dbDataAdapter.FillSchema(dataTable, SchemaType.Mapped);

      dbDataAdapter.Fill(dataTable);

      //dataGridView1.Columns.Clear();
      //dataGridView1.Rows.Clear();

      dataGridView1.DataSource = dataTable;

    }

    private DbCommand GetDbSqlCommand(string formatsql)
    {
      DbCommand dbCommand = connection.CreateCommand();
      dbCommand.Connection = connection;
      dbCommand.CommandText = formatsql;
      dbCommand.CommandTimeout = 30;

      return dbCommand;
    }

  }
}
